package edu.hcmus.sow.dao;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import edu.hcmus.sow.domain.UserProfile;

/**
 * DAO to manage UserProfile entities.
 * 
 */
@Repository
@Transactional
public class UserProfileDAOImpl extends AbstractHibernateDAO<UserProfile, Integer> implements UserProfileDAO {

   public List<UserProfile> findByName(Integer clientID, String name) throws DataAccessException {
      String queryString = "from UserProfile up join fetch up.userByUserId u where u.clientID = ? and concat(up.firstName, ' ', up.lastName) like ?";
      List<UserProfile> list = executeQuery(queryString, 0, 5, clientID, name + "%");
      return list;
   }

   public UserProfile getByUserID(Integer userID) throws DataAccessException {
      String queryString = "from UserProfile up join fetch up.userByUserId u where u.id=?";
      List<UserProfile> list = executeQuery(queryString, userID);
      return list.size() == 0 ? null : list.get(0);
   }

   public List<UserProfile> findByCriteria(Integer clientId, String firstName, String lastName, String username,
         Integer groupId) throws DataAccessException {

      if (groupId == null) {
         String query = "from UserProfile up join fetch up.userByUserId u ";
         query += "where u.clientID = ? and up.firstName like ? and up.lastName like ? and u.username like ?";
         return executeQuery(query, clientId, firstName + "%", lastName + "%", username + "%");
      } else {
         String query = "select up from UserProfile up join fetch up.userByUserId u inner join u.userGroups ug ";
         query += "where u.clientID = ? and up.firstName like ? and up.lastName like ? and u.username like ? and ug.groupID = ?";
         return executeQuery(query, clientId, firstName + "%", lastName + "%", username + "%", groupId);
      }
   }
}
